package uk.gov.swmprobation.cplitebase;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import uk.gov.swmprobation.cplitebase.R;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.ListFragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.Tab;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.analytics.tracking.android.MapBuilder;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;

public class MainActivity extends MyActivity {

	    static TabAdapter tabAdapter;
	    ViewPager viewPager;
	    ActionBar actionBar;
	    static List<Integer> projectTypes;
		private BroadcastReceiver backgroundUpdate;
		Intent MQTTIntent;
		private static final int SELECT_IMAGE = 0;
		Intent locationService;
		private final static int CONNECTION_FAILURE= 999;
		private int currentTab = 0;

	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.activity_main);
	        	        
	        locationService = new Intent(this,LocationServicesWithClient.class); 
	        
	        // Create the adapter that will return a fragment for each of the three primary sections
	        // of the app.
	        tabAdapter = new TabAdapter(getSupportFragmentManager());
	        
	        // Set up the action bar.
	        actionBar = getSupportActionBar();

	        // Specify that the Home/Up button should not be enabled, since there is no hierarchical
	        // parent.
	        actionBar.setHomeButtonEnabled(false);
	        actionBar.setDisplayHomeAsUpEnabled(false);

	        // Specify that we will be displaying tabs in the action bar.
	        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

	        
	        if (savedInstanceState!=null){
	        	currentTab = savedInstanceState.getInt("tab");
	        }
	        // Set up the ViewPager, attaching the adapter and setting up a listener for when the
	        // user swipes between sections.
	        viewPager = (ViewPager) findViewById(R.id.tabs);
	        viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
	            @Override
	            public void onPageSelected(int position) {
	                // When swiping between different app sections, select the corresponding tab.
	                // We can also use ActionBar.Tab#select() to do this if we have a reference to the
	                // Tab.
	            	if(actionBar.getTabCount()>0){
	            		actionBar.setSelectedNavigationItem(position);
	            	}
	            }
	        });

	        backgroundUpdate = new BroadcastReceiver(){

				@Override
				public void onReceive(Context context, Intent intent) {
					setViews();				
					abortBroadcast();
				}
	        	
	        }; 
			
	    }

	    public void onPause(){
	    	super.onPause();
	    	unregisterReceiver(backgroundUpdate);
	    	if(Helper.dialog != null){
	    		Helper.dialog.dismiss();
	    	}
	    	this.stopService(locationService);
	    }
	    
	    public void onDestroy(){
	    	super.onDestroy();
	    }
	    
	    @Override
	    public void onResume(){
	    	super.onResume();
	    	if(checkPlayServices()){
	    		startService(locationService);
	    	}
	    	if (sharedPref.getBoolean(SettingsActivity.startHintTitle, true)){
				Helper.showHintDialog(this, SettingsActivity.startHintTitle, SettingsActivity.startHintMessage, SettingsActivity.startHintIcon);
			}
	    	setViews();
	    	IntentFilter intentFilter = new IntentFilter();
	        intentFilter.addAction("uk.gov.swmprobation.cpvisibility.event.updatemain");
	        intentFilter.setPriority(1);
	        registerReceiver(backgroundUpdate, intentFilter);
	    }

	    @Override
		public void onSaveInstanceState(Bundle savedInstanceState) {
		  super.onSaveInstanceState(savedInstanceState);
		  savedInstanceState.putInt("tab", actionBar.getSelectedTab().getPosition());
		}
	    
	    @Override
	    public boolean onCreateOptionsMenu(Menu menu) {
	        // Inflate the menu items for use in the action bar
	        MenuInflater inflater = getMenuInflater();
	        inflater.inflate(R.menu.application_menu, menu);
	        return super.onCreateOptionsMenu(menu);
	    }
	    
	    @Override
	    public boolean onOptionsItemSelected(MenuItem item) {
	        // Handle item selection
	    	int itemID = item.getItemId();
	        if (itemID == R.id.action_camera) {
				easyTracker.send(MapBuilder
					      .createEvent("user_action",     // Event category (required)
					                   "start_camera",  // Event action (required)
					                   "actionbar",   // Event label
					                   getDuration())            // Event value
					      .build()
					  );
				return callCamera();
			} else {
				return super.onOptionsItemSelected(item);
			}
	    }
	    
	    private boolean checkPlayServices(){
			int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
			if (ConnectionResult.SUCCESS == resultCode) {
	            return true;
	        } else {
	        	Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(resultCode, this, CONNECTION_FAILURE);
	        	if (errorDialog != null) {
	                // Create a new DialogFragment for the error dialog
	                ErrorDialogFragment errorFragment = new ErrorDialogFragment();
	                // Set the dialog in the DialogFragment
	                errorFragment.setDialog(errorDialog);
	                // Show the error dialog in the DialogFragment
	                errorFragment.show(getSupportFragmentManager(),
	                        "Location Updates");
	            }
	        	return false;
	        }
		}
	    
	    public static class ErrorDialogFragment extends DialogFragment {
	        // Global field to contain the error dialog
	        private Dialog mDialog;
	        // Default constructor. Sets the dialog field to null
	        public ErrorDialogFragment() {
	            super();
	            mDialog = null;
	        }
	        // Set the dialog to display
	        public void setDialog(Dialog dialog) {
	            mDialog = dialog;
	        }
	        // Return a Dialog to the DialogFragment.
	        @Override
	        public Dialog onCreateDialog(Bundle savedInstanceState) {
	            return mDialog;
	        }
	    }
	    
	    public void TakePhotoButton(View v){
	    	easyTracker.send(MapBuilder
	    		      .createEvent("user_action",     // Event category (required)
	    		                   "start_camera",  // Event action (required)
	    		                   "screenicon",   // Event label
	    		                   getDuration())            // Event value
	    		      .build()
	    		  );
	    	
	    	easyTracker.send(MapBuilder.createAppView()
	    		      .build()
	    		  );
	    	callCamera();    	
	    }
	    
	        public boolean callCamera(){
        	
	        	if(Helper.isAirplaneModeOn(this)){
	        		Toast.makeText(this, "Please turn of Airplane mode to continue.", Toast.LENGTH_SHORT).show();
	    	    	return true;
	        	}
	        	
	        	Intent takePictureIntent = new Intent(this, TakePhoto.class);
	        	startActivity(takePictureIntent);

	            return true;
	    	}    
	        
	    private void setViews(){
	    	
	    	actionBar.removeAllTabs();
	    	projectTypes = DatabaseHandler.getProjectTypes();
	    	tabAdapter.notifyDataSetChanged();
	    	viewPager.setAdapter(tabAdapter);
	        for (int i = 0; i < tabAdapter.getCount(); i++) {
	            actionBar.addTab(
	                    actionBar.newTab()
	                            .setText(tabAdapter.getPageTitle(i))
	                            .setTabListener(this));
	        }
	        
	        
	        actionBar.getTabAt(currentTab).select();
	        
	    }

	    public static class TabAdapter extends FragmentPagerAdapter {
	    	
	        public TabAdapter(FragmentManager fm) {
	            super(fm);
	        }

	        @Override
	        public Fragment getItem(int position) {
		        Fragment fragment = new TabFragment();
		        Bundle args = new Bundle();
		        args.putInt(TabFragment.PROJECT_TYPE, position+1);
		        fragment.setArguments(args);
		        return fragment;
	        }

	        @Override
	        public int getCount() {
	            return Project.TYPE_NAMES.length-1;
	        }

	        @Override
	        public CharSequence getPageTitle(int position) {
	            return Project.TYPE_NAMES[position+1];
	        }
	    }

	    
	    public static class TabFragment extends ListFragment {

	        public static final String PROJECT_TYPE = "project_type";
	    	private List<Project> projects;
	    	Context context;

	        @Override
	        public View onCreateView(LayoutInflater inflater, ViewGroup container,
	                Bundle savedInstanceState) {
	            View rootView = inflater.inflate(R.layout.fragment_main_activity, container, false);
	            Bundle args = getArguments();
	            context = getActivity();
	            setListAdapter(new ProjectListAdapter(args.getInt(TabFragment.PROJECT_TYPE)));
	            
	            return rootView;
	        }
	        
	        @Override 
	        public void onListItemClick(ListView parent, View v, int position, long id){
	        	if(Helper.isNetworkAvailable(context)){
		        	Project projectToOpen = projects.get(position);
		        	Intent openProjectView;
		        	
		        	if (projectToOpen.getProjectType()==Project.TYPE_DRAFT) {
		        		openProjectView = new Intent(context, CreateProject.class);
		        		int idToOpen = projectToOpen.getId();
		        		openProjectView.putExtra("id", idToOpen);
		        	} else {        		
		        		openProjectView = new Intent(context, ReviewProjects.class);
		        		openProjectView.putExtra("position", position);
		        		openProjectView.putExtra("updated", projectToOpen.getUpdated());
		        		
		        	}
		      	    startActivity(openProjectView);
		    
	        	} else {
	        		Toast.makeText(context, "Can't connect to Internet, please try again later.", Toast.LENGTH_LONG).show();
	        	}
	        }
	        
	        private class ProjectListAdapter extends BaseAdapter{
	        	
	        	ProjectListAdapter(int type) {
	        		projects = DatabaseHandler.getTypeProjects(type);
	        	}
	        	
	    			@Override
	    			public int getCount() {
	    				return projects.size();
	    			}

	    			@Override
	    			public Object getItem(int pos) {
	    				return projects.get(pos);
	    			}

	    			@Override
	    			public long getItemId(int pos) {
	    				return pos;
	    			}

	    			@Override
	    			public View getView(int pos, View view, ViewGroup viewGroup) {
	    				view = View.inflate(context, R.layout.projectlist_item, null);
	    				
	    				if(pos % 2 == 1){
	    					view.setBackgroundResource(R.drawable.linkbackgroundodd);
	    				} else {
	    					view.setBackgroundResource(R.drawable.linkbackgroundeven);
	    				}
	    				
	    				Project project = (Project) getItem(pos);
	    				
	    				TextView text = (TextView) view.findViewById(R.id.local_id);
	    	            text.setText(String.valueOf(project.getId()));
	    	            String describeProject;
	    				if (!project.getProjectStatus().equals("Draft")){
	    					describeProject=project.getProjectId() + " - " + Helper.shortName(project.getProjectName());
	    				} else {
	    					describeProject=project.getProjectName();
	    				}
	    	            
	    	            
	    				text = (TextView) view.findViewById(R.id.project_name);
	    	            text.setText(describeProject);

	    	            ImageView  image = (ImageView) view.findViewById(R.id.project_status);
	    	             if (project.getProjectStatus().equals("Waiting")) {
	    	            	image.setImageResource(android.R.drawable.ic_dialog_email);
	    	            	image.setVisibility(View.VISIBLE);
	    	             }
	    	            
	    	            ImageButton button = (ImageButton) view.findViewById(R.id.delete_button);
	    				button.setFocusable(false);
	    		
	    	            return view;
	    			}};
	    			
	    }

		@Override
		public void onTabReselected(Tab arg0,
				android.support.v4.app.FragmentTransaction arg1) {
		}

		@Override
		public void onTabSelected(Tab tab,
				android.support.v4.app.FragmentTransaction arg1) {
			viewPager.setCurrentItem(tab.getPosition());
		}

		@Override
		public void onTabUnselected(Tab arg0,
				android.support.v4.app.FragmentTransaction arg1) {
		}
		
			    
	    public void deleteProject(View v) 
	    {
	        //get the row the clicked button is in
	        RelativeLayout parentRow = (RelativeLayout)v.getParent();
	        
	        TextView idText = (TextView) parentRow.getChildAt(0);
	        
	        final int localId = Integer.parseInt((String) idText.getText());
	        
	        final Project projectToDelete = DatabaseHandler.getProject(localId);
	        
	        final String projectName = projectToDelete.getProjectName();

			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Are you sure you want to delete "+projectName+"?");
		    builder.setTitle("Delete project?");
			builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			        	   	DatabaseHandler.deleteProject(localId);
			        	   	setViews();
			           }
			       });
			builder.setNegativeButton("Not Now", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			           }
			       });

			AlertDialog dialog = builder.create();
			dialog.show();
	    }
	    
	    /** Create a File for saving an image or video */
	    @SuppressLint("SimpleDateFormat")
		private static File getOutputMediaFile(){
	    	File mediaFile;
	        //Check SDCard is mounted
	    	String state = Environment.getExternalStorageState();

	    	if (state.equals(Environment.MEDIA_MOUNTED)) {
		        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
		                  Environment.DIRECTORY_PICTURES), "GCP");
				        
		        // Create the storage directory if it does not exist
		        if (! mediaStorageDir.exists()){
		            if (! mediaStorageDir.mkdirs()){
		                return null;
		            }
		        }
		
		        // Create a media file name
		        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
		        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");
	    	} else {
	    		Toast.makeText(MyApplication.getContext(), "Can't access your SD card", Toast.LENGTH_LONG).show();
	    		return null;
	    	}
	    	sharedPref.edit().putString("filePath", mediaFile.getPath());
	        return mediaFile;
	    }
		
	    @Override
		public void onActivityResult(int requestCode, int resultCode, Intent data) {
		  super.onActivityResult(requestCode, resultCode, data);
		  if (requestCode == SELECT_IMAGE)
		    if (resultCode == Activity.RESULT_OK) {

		    //Get GPS co-ordinates
		      double lat = LocationServicesWithClient.getLocationLat();
			  double lng = LocationServicesWithClient.getLocationLng();
			  String filePath = sharedPref.getString("filePath", "");
			  if(filePath!="" && PhotoTools.photoExists(filePath)){
				  Project newproject = new Project(filePath, lat, lng);
				  sharedPref.edit().remove("filePath");
				  newproject.save();
				  if (Helper.isNetworkAvailable(this)){
				    	//If pass open next activity
					      Intent createProject = new Intent(this, CreateProject.class);
					      createProject.putExtra("id", newproject.getId());
					      startActivity(createProject);
				      } else {
				    	  Toast.makeText(this, "Can't access internet - Project saved to drafts.", Toast.LENGTH_LONG).show();
				      }
			  } else {
				  Toast.makeText(this, "Can't access photo - Please try again.", Toast.LENGTH_LONG).show();
			  }    
		    } 
		  		  
		}
	    
	}

